package com.dev118.jexample.mongodb.util;

import org.springframework.data.mongodb.core.MongoTemplate;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

/**
 * @author Wenchuanke
 *
 */
public class SequenceUtil {

	private MongoTemplate template;

	public SequenceUtil() {

	}

	public SequenceUtil(MongoTemplate mongoTemplate) {
		this.template = mongoTemplate;
	}

	public int getSequence(String collectionName) {

		DBCollection collection = template.getCollection("sequence");
		DBObject query = new BasicDBObject("coll_name", collectionName);
		DBObject update = new BasicDBObject("$inc", new BasicDBObject().append(
				"val", 1));
		DBObject doc = collection.findAndModify(query, update);

		if (doc == null) {

			// 如果当前Collection没有Sequence记录，则自动添加
			DBObject row = new BasicDBObject();
			row.put("coll_name", collectionName);
			row.put("val", 0);
			collection.insert(row);
			return getSequence(collectionName);

		} else {
			return (Integer) doc.get("val") + 1;
		}
	}
}
